<!-- 目标管理页面 -->
<template>
  <div>
    
    <hoemIndex
      :target-list="targetList"
      :search-query="searchQuery"
      @submit="handleFormSubmit"
      @update="handleUpdate"
      @search="handleSearch"
      @delete="handleDelete"
    ></hoemIndex>
    <!-- 显示目标列表 -->
  </div>
</template>
<script>
import hoemIndex from "@/components/home.vue";
import {
  getTargetList,
  insertgetList,
  servegetList,
  updategetList,
  deletegetList,
} from "@/api/target/target.js"; // 引入接口方法
export default {
  components: {
    hoemIndex,
  },
  data() {
    return {
      targetList: [], // 存储目标列表
      searchQuery: { country: "" }, // 搜索框绑定的数据（对象形式）
      id:"",
    };
  },
  mounted() {
    this.fetchTargetList(); // 调用方法获取目标列表
  },
  methods: {
    async fetchTargetList() {
      try {
        const response = await getTargetList();
        this.targetList = response.data; // 假设接口返回的数据在 data 属性中
        console.log("目标列表:", this.targetList);
      } catch (error) {
        console.error("获取目标列表失败:", error);
      }
    },
    async handleFormSubmit(formData) {
      console.log("接收到的表单数据:", formData);
      try {
        const response = await insertgetList(formData);
        this.fetchTargetList(); // 重新获取目标列表
        this.$message.success("添加成功");
      } catch (error) {
        console.error("插入目标列表失败:", error);
      }
    },
    async handleUpdate(formData) {
      console.log("接收到的更新数据:", formData);
      try {
        const response = await updategetList(formData);
        this.fetchTargetList(); // 重新获取目标列表
        this.$message.success("更新成功");
      } catch (error) {
        console.error("更新目标列表失败:", error);
      }
    },
    async handleSearch(searchQuery) {
      try {
        console.log("搜索参数:", searchQuery);
        const response = await servegetList(searchQuery); // 调用 GET 请求
        this.targetList = response.data; // 更新目标列表
        console.log("搜索结果:", response);
      } catch (error) {
        console.error("搜索失败:", error);
      }
      if(!searchQuery){
        this.fetchTargetList();
      }
    },
    async handleDelete(id) {
      try {
        await this.$confirm("此操作将永久删除该条记录, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        const response = await deletegetList({ id }); // 以 JSON 格式传递参数
        console.log("删除目标成功:", response);
        this.fetchTargetList(); // 重新获取目标列表
        this.$message.success("删除成功");
      } catch (error) {
        console.error("删除目标失败:", error);
      }
    },
  },
};
</script>
<style></style>
